package alibaba;

import com.sun.org.apache.regexp.internal.RE;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Main2 {

    public static void main(String[] args) throws Exception{
        BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
        String s = buf.readLine();
        String[] ss = s.split(" ");
        int n = Integer.parseInt(ss[0]);
        int m = Integer.parseInt(ss[1]);
        int[][] graph = new int[n + 1][m + 1];
        for (int i = 1; i <= n; i++){
            s = buf.readLine();
            for (int j = 1; j <= m; j++){
                graph[i][j] = s.charAt(j - 1) - '0';
            }
        }
        s = buf.readLine();
        int k = Integer.parseInt(s);
        List<Node> list = new ArrayList<>(k);
        for (int i = 0; i < k; i++){
            s = buf.readLine();
            ss = s.split(" ");
            list.add(new Node(Integer.parseInt(ss[0]), Integer.parseInt(ss[1]), 0));
        }
        int res = Integer.MAX_VALUE;
        for (int i = 1; i <= n; i++){
            for (int j = 1; j <= m; j++){
                Node target = new Node(i, j, 0);
                int maxTime = 0;
                for (Node node : list) {
                    boolean[][] visited = new boolean[n + 1][m + 1];
                    int tmp = bfs(node, target, graph, visited, n, m);
                    maxTime = Math.max(maxTime, tmp);
                }
                res = Math.min(res, maxTime);
            }
        }
        System.out.println(res==Integer.MAX_VALUE? -1 : res);
    }
    static class Node{
        int x;
        int y;
        int level;
        Node(int x, int y, int level){
            this.x = x;
            this.y = y;
            this.level = level;
        }
    }

    public static int bfs(Node source, Node target, int[][] graph, boolean[][] visited, int n, int m){
        int[] flag = new int[]{1, -1, -1, 1, 1};
        Queue<Node> queue = new LinkedList<>();
        queue.offer(source);
        while (!queue.isEmpty()){
            Node node = queue.poll();
            if (node.x == target.x && node.y == target.y){
                return node.level;
            }
            for (int i = 0; i < 4; i++){
                int a = flag[i];
                int b = flag[i + 1];
                if (node.x + a >= 0 && node.x + a <= n && node.y + b >= 0 && node.y + b <= m && graph[node.x + a][node.y + b] == 0 && !visited[node.x + a][node.y + b]){
                    queue.offer(new Node(node.x + a, node.y + b, node.level + 1));
                    visited[node.x + a][node.y + b] = true;
                }
            }
        }
        return Integer.MAX_VALUE;
    }
}
